import uuid

import gitlab
import jenkins
import requests

from model.jenkins_kube_info import JenkinsKubeInfo

from config import Config

conf = Config()
# 定义容器规格
Tier = {
    "0.5": "-Xmx500m -Xms500m",
    "1": "-Xmx1g -Xms1g",
    "2": "-Xmx2g -Xms2g",
    "4": "-Xmx4g -Xms4g",
    "8": "-Xmx8g -Xms8g",
}

# 定义一些配置片段
CD_str = """stage('Deploy to K8S'){
        if(profiles == 'pre'){
            echo '接下来进行K8s预发环境的发布...'
            sh '''
                sed -i "/image/{s/__VERSION__/${version}/}" k8s-config.yaml
            '''
            kubernetesDeploy configs: 'k8s-config.yaml', kubeConfig: [path: ''], kubeconfigId: 'KUBE_ID', secretName: '', ssh: [sshCredentialsId: '*', sshServer: ''], textCredentials: [certificateAuthorityData: '', clientCertificateData: '', clientKeyData: '', serverUrl: 'https://']
        }
    }"""

Maven_build_str = """stage('Maven Build'){
        echo '开始编译...'
        sh "mvn clean -U package  -Dversion=${version} -Dmaven.test.skip=true"
    }
    stage('SonarQube analysis'){
        echo '开始代码扫描...'
        withSonarQubeEnv('SonarQube') {
            sh "mvn sonar:sonar"
        }
    }"""

Npm_build_str = """stage('Npm Build & Update'){
        echo '开始编译...'
        sh '''
            rm -rf dist
            npm config set registry https://registry.cnpm.cspiretech.com
            npm install
            npm run build:${profiles}
        '''
    }
    stage('SonarQube analysis') {
        withSonarQubeEnv('SonarQube') {
            sh '''
                ${scanner_path}/bin/sonar-scanner  -Dsonar.projectKey=${JOB_BASE_NAME}
            '''
        }
    }"""


# 创建Job
# server.create_job('empty', jenkins.EMPTY_CONFIG_XML)
# jobs = server.get_jobs()
# print(jobs)

# 获取job
# my_job = server.get_job_config('new')
# print(my_job) # prints XML configuration

# 实例化jenkins服务器对象
def jenkins_conn():
    server = jenkins.Jenkins(conf.JENKINS_URL, username=conf.JENKINS_USER, password=conf.JENKINS_PASSWD)  # 公司 Jenkins正式环境
    user = server.get_whoami()
    version = server.get_version()
    print('Hello %s from Jenkins %s' % (user['fullName'], version))
    return server


def create_jenkins_job(job_name, job_desc, code_repo, conf_repo):
    # 实例化jenkins服务器连接
    try:
        server = jenkins_conn()
    except Exception as e:
        print(e)
        return
    # 根据模板文件，创建jenkins的job
    file_job = "../../static/cicd/job.xml"
    with open(file_job) as file:
        text = file.read()
        text = text.replace("__UUID__", str(uuid.uuid1()))
        text = text.replace("__CODE_REPO__", code_repo)
        text = text.replace("__CONF_REPO__", conf_repo)
        text = text.replace("__APP_NAME__", job_name)
        text = text.replace("__DESC__", job_desc)
        print(text)
        try:
            server.create_job(job_name, text)
        except Exception as e:
            print(e)


def create_gitlab_file(kube_id, cluster_ns, app_name, node_port, code_repo, conf_repo, image, pre_cd=True,
                       build_tool='maven', tier=1, include_arm64=False):
    # 判断是前端还是后端，提供不同的模板
    if build_tool == 'maven':
        file_dockerfile = '../../static/cicd/Dockerfile_java'
        file_k8s = "../../static/cicd/k8s_java.yaml"
    elif build_tool == 'npm':
        file_dockerfile = '../../static/cicd/Dockerfile_nginx'
        file_k8s = ".../static/cicd/k8s_nginx.yaml"
    file_jenkinsfile = "../../static/cicd/Jenkinsfile.groovy"

    j = JenkinsKubeInfo()
    k = j.find_by_kube_id(kube_id)
    cluster_code = k["name"]

    # 实例化gitlab
    url = conf.GITLAB_URL
    token = conf.GITLAB_TOKEN
    prj_id = conf.GITLAB_JENKINS_PROJECT_ID
    prj_brach = conf.GITLAB_JENKINS_PROJECT_BRANCH
    proxy = conf.GITLAB_PROXY

    if proxy:
        session = requests.Session()
        session.proxies = {
            "https": proxy,
            "http": proxy,
        }
        gl = gitlab.Gitlab(url=url, private_token=token, session=session)
    else:
        gl = gitlab.Gitlab(url=url, private_token=token)
    project = gl.projects.get(prj_id)  # config repo的项目id
    branch = prj_brach

    # 转化image，去掉tag
    image = image.split(":")[0]

    # 生成Jenkinsfile
    with open(file_jenkinsfile) as file:
        text = file.read()
        if pre_cd:
            text = text.replace("stage('Deploy to K8S'){}", CD_str)
            text = text.replace("__KUBE_ID__", kube_id)  # 根据CLUSTER找到KUBE_ID
        if build_tool == 'maven':
            text = text.replace("stage('Build & Scan'){}", Maven_build_str)
        elif build_tool == 'npm':
            text = text.replace("stage('Build & Scan'){}", Npm_build_str)
        if include_arm64:
            # 包含arm64，本质是一个镜像manifest中包括两个镜像，一个是amd64的，一个是arm64的
            text = text.replace("--platform linux/amd64", "--platform linux/amd64,linux/arm64")
        text = text.replace("__CODE_REPO__", code_repo)
        text = text.replace("__CONF_REPO__", conf_repo)
        text = text.replace("__APP_NAME__", app_name)
        text = text.replace("__CLUSTER__", cluster_code)
        text = text.replace("__IMAGE__", image)
        print(text)
        try:
            project.files.create({'file_path': cluster_code + '/' + app_name + '/Jenkinsfile',
                                  'branch': branch,
                                  'content': text,
                                  'author_email': 'python-gitlab@123.com',
                                  'author_name': 'python-gitlab',
                                  'commit_message': 'Create Jenkinsfile'})
        except Exception as e:
            print(e)

    # 生成Dockerfile
    with open(file_dockerfile) as file:
        text = file.read()
        text = text.replace("__APP_NAME__", app_name)
        text = text.replace("-Xmx1g -Xms1g", Tier[tier])
        print(text)
        try:
            project.files.create({'file_path': cluster_code + '/' + app_name + '/Dockerfile',
                                  'branch': branch,
                                  'content': text,
                                  'author_email': 'python-gitlab@123.com',
                                  'author_name': 'python-gitlab',
                                  'commit_message': 'Create Dockerfile'})
        except Exception as e:
            print(e)

    # 生成K8s yaml
    with open(file_k8s) as file:
        text = file.read()
        text = text.replace("__NAME__", app_name)
        text = text.replace("__NAMESPACE__", cluster_ns)
        text = text.replace("__PORT__", node_port)
        print(text)
        try:
            project.files.create({'file_path': cluster_code + '/' + app_name + '/k8s-config.yaml',
                                  'branch': branch,
                                  'content': text,
                                  'author_email': 'python-gitlab@123.com',
                                  'author_name': 'python-gitlab',
                                  'commit_message': 'Create k8s.yaml'})
        except Exception as e:
            print(e)


# if __name__ == '__main__':
    # create_jenkins_job(
    #     'newjob002',
    #     '测试工程',
    #     'http://129.211.170.226:8080/root/test-flask.git',
    #     'http://129.211.170.226:8080/root/jenkins-repo.git'
    # )
    # create_gitlab_file(
    #     'hz-zczd',
    #     'backend',
    #     'zczd-service-hahaha',
    #     '40098',
    #     'http://129.211.170.226:8080/root/test-flask.git',
    #     'http://129.211.170.226:8080/root/jenkins-repo.git',
    #     'harbor.yunyang.com.cn/zczd/some-image:1.1',
    #     pre_cd=False,
    #     build_tool='maven',
    #     tier=4,
    #     include_arm64=False,
    # )

# https://gitlab2.cspiretech.com/ops/Jenkins-repo.git
